package thread;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class RaceMain extends JFrame {

	JLabel img1 = new JLabel(new ImageIcon("1.bmp"));
	JLabel img2 = new JLabel(new ImageIcon("2.bmp"));
	JLabel img3 = new JLabel(new ImageIcon("3.bmp"));
	int rank = 0;
	
	
	private JPanel contentPane;
	private JButton btnNewButton;
	private JPanel panel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					RaceMain frame = new RaceMain();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public RaceMain() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.add(getBtnNewButton(), BorderLayout.SOUTH);
		contentPane.add(getPanel(), BorderLayout.CENTER);
		
		img1.setBounds(10,50,50,50);
		img2.setBounds(10,110,50,50);
		img3.setBounds(10,170,50,50);
		
		panel.add(img1);
		panel.add(img2);
		panel.add(img3);
		
	}

	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("Statr");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					rank = 0;
					new ImagMove(img1).start();
					new ImagMove(img2).start();
					new ImagMove(img3).start();
				}
			});
		}
		return btnNewButton;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(null);
		}
		return panel;
	}
	
	class ImagMove extends Thread{
		JLabel img;
		
		public ImagMove(JLabel l){
			this.img = l;
		}
		@Override
		public void run(){
			img.setLocation(10, img.getY());
			Random rnd = new Random();
			
			int x = 0;
			while(true){
				x = rnd.nextInt(60);
				int mx = img.getX()+x;
				img.setLocation(mx, img.getY());
				if(mx>panel.getWidth() -30-img.getWidth()){
					rank++;
					img.setToolTipText("등수 : " + rank);
					break;
				}
				try{
					sleep(1000);
				}catch(Exception ex){
					
				}
			}
		}
	}
}
